package com.sy.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Author yumax
 * @Date 2024 01 08 09 56
 **/
@Slf4j
public class EventLoopClient2 {
    public static void main(String[] args) throws InterruptedException, IOException {
        final NioEventLoopGroup group = new NioEventLoopGroup();
        final ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        sc.pipeline().addLast(new StringEncoder());
                    }
                })
                //1.连接到服务器
                // 异步非阻塞，main 发起了调用，真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8989));
        final long start = System.currentTimeMillis();
        //2.1 使用sync方法同步处理结果
        channelFuture.sync(); //阻塞住当前线程，直到nio线程连接建立完毕
        // 无阻塞向下执行获取channel
        final Channel sc = channelFuture.channel();
        log.debug("sc ..{}", sc);
        //2. 向服务器发送数据
        new Thread(() -> {
            final Scanner scanner = new Scanner(System.in);
            while (true) {
                final String line = scanner.nextLine();
                if ("q".equals(line)) {
                    sc.close(); //close 异步操作
                    //log.debug("处理关闭之后的操作"); //不能在这里善后
                    break;
                }
                sc.writeAndFlush(line);
            }

        }, "sender").start();

        final ChannelFuture closeFuture = sc.closeFuture();
        /*
        log.debug("waiting close");
        closeFuture.sync();
        log.debug("处理关闭之后的操作");

        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("处理关闭之后的操作");
            }
        });
         */
        closeFuture.addListener(future -> {
            log.debug("处理关闭之后的操作");
            group.shutdownGracefully();
        });
    }
}
